var _ = require('lodash');
var workspaceListeners = [];
var config = require('../../../config.json');
var request = require('request');
var logger = require('log4js').getLogger();
/**
 * 工作空间更新依赖时调用监听接口
 * 构建模块需要使用
 * @type {Array}
 */

exports.addUpdateListener = function (l) {
    if ('function' === l) {
        workspaceListeners.push(l);
    }
}
exports.removeUpdateListener = function (l) {
    var index = _.indexOf(l);
    if (index >= 0) {
        workspaceListeners.splice(index, 1);
    }
}
exports.fireWorkspaceUpdate = function (id) {
    _.forEach(workspaceListeners, function (l) {
        if (l) {
            l(id);
        }
    });
}

exports.notifyEnzyme = function (work_name, cb) {
    var port = config.server.server_port;
    if (port.length > 0) {
        port = ":" + port;
    }
    var url = "http://" + config.server.server_host + port + "/api/workspace/" + work_name;
    request({
        uri: url,
        headers: {"Enzyme-Options": "reload-target"},
        method: "PUT"
    }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            cb(null, response.body);
        } else {
            logger.error(error);
            cb('通知enzyme失败');
        }
    });
}